import random
import os
import string

class GenerateWordsUtil:

    def __init__(self):

        self.words = []

        self.generated_names = set()  # 用于存储已生成的名称

        # 使用绝对路径打开文件
        current_dir = os.path.dirname(os.path.abspath(__file__))
        words_path = os.path.join(current_dir, 'words.txt')
        with open(words_path, 'r', encoding='utf-8') as f:
            self.words = [line.strip().lower() for line in f if line.strip()]
    
    def generate_words(self, num_words=1, uikit_type=None, prefix=None):
        # 从单词列表中随机选择num_words个单词
        selected_words = random.sample(self.words, num_words)
        # 打乱单词的顺序
        random.shuffle(selected_words)
        # 生成名称 , 驼峰命名

        # 修复：正确使用upper_first_letter方法处理后续单词，并用空字符串连接
        word = selected_words[0]
        if len(selected_words) > 1:
            for w in selected_words[1:]:
                word += GenerateWordsUtil.upper_first_letter(w)

        name = ''

        if uikit_type:
            suffix = 'View'
            if uikit_type == 'UILabel':
                suffix = 'Label'
            elif uikit_type == 'UITextField':
                suffix = random.choice(['TextField', 'TextInput', 'TF'])
            elif uikit_type == 'UIButton':
                suffix = random.choice(['Button', 'Btn'])
            elif uikit_type == 'UIImageView':
                suffix = random.choice(['ImageView', 'ImgView'])
            elif uikit_type == 'UITableView':
                suffix = random.choice(['TableView', 'Table'])
            elif uikit_type == 'UICollectionView':
                suffix = 'CollectionView'

            name = word + suffix
        else:
            name = word

        if prefix:
            name = prefix + GenerateWordsUtil.upper_first_letter(name)
        
        # 确保生成的名称是唯一的
        while name in self.generated_names:
            a = random.choice(string.ascii_lowercase)
            name = a + name
        # 将生成的名称添加到集合中
        self.generated_names.add(name)
        return name
    
    @staticmethod
    def lower_first_letter(s):
        if not s:  # 如果字符串为空，直接返回
            return s
        return s[0].lower() + s[1:]

    @staticmethod
    def upper_first_letter(s):
        if not s:  # 如果字符串为空，直接返回
            return s
        return s[0].upper() + s[1:]
        

if __name__ == '__main__':
    gen_words = GenerateWordsUtil()
    name = random.choice(gen_words.words)  # shuffle直接修改列表，不返回值
    print(name)  # 打印打乱后的列表